package com.lyk.swap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.lyk.swap.orm.Price;
import com.lyk.swap.orm.Trade;
import com.lyk.swap.struts.action.BaseAction;

public class RiskProfit extends Trade {
	/**
	 * 
	 */
	private static final long serialVersionUID = -343856592884386304L;
	private List<int[]> workdayinfo;
	private double risk;
	private double cp;
	private double profit;
	private String murl;
	public static final String SURL = "http://www.cmegroup.com/CmeWS/md/MDServer/V1/Venue/G/Exchange/XNYM/FOI/FUT/Product/CL?currentTime=";
	public static final String TICKERHEDDER = "CL";
	public static final String MURL = "&contractCDs=";

	@SuppressWarnings("deprecation")
	public RiskProfit(Trade trade) throws IOException {
		super(trade);
		workdayinfo = WorkdayCalc.workdayCalc(start, end,
				Calendar.getInstance());
		int year = start.getYear() - 110, month = start.getMonth() + 1, minus = 0;
		murl = new String(MURL);
		for (int i = 0; i < workdayinfo.size(); i++) {
			StringBuilder sb = new StringBuilder(TICKERHEDDER);
			if (month + i - minus * 12 > 11) {
				minus++;
				year++;
			}
			sb.append(BaseAction.TICKER[month + i - minus * 12]);
			sb.append(year);
			murl += sb.toString();
			if (i != workdayinfo.size() - 1) {
				murl += ",";
			}
		}
		calculate();
	}

	@SuppressWarnings("deprecation")
	public void calculate() throws IOException {
		cp = 0;
		Date date = new Date();
		List<Double> currentprice = new ArrayList<Double>();
		String surl = new String(SURL);
		surl += date.getTime();
		surl += murl;
		URL url = new URL(surl);
		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
		InputStreamReader input = new InputStreamReader(
				httpConn.getInputStream(), "utf-8");
		BufferedReader br = new BufferedReader(input);
		String s = br.readLine();
		httpConn.disconnect();
		if (workdayinfo.size() == 1) {
			JSONObject jo = JSONObject.fromObject(s)
					.getJSONObject("marketDataInfoAsStringList")
					.getJSONObject("message");
			String sprice = jo.getString("settlePrice");
			if (sprice.equals("-")) {
				sprice = jo.getString("tradePrice");
			}
			if (sprice.equals("-")) {
				sprice = "0";
			}
			currentprice.add(Double.parseDouble(sprice));
		} else {
			JSONArray ja = JSONObject.fromObject(s)
					.getJSONObject("marketDataInfoAsStringList")
					.getJSONArray("message");
			for (int i = 0; i < ja.size(); i++) {
				JSONObject jo = ja.getJSONObject(i);
				String sprice = jo.getString("settlePrice");
				if (sprice.equals("-")) {
					sprice = jo.getString("tradePrice");
				}
				if (sprice.equals("-")) {
					sprice = "0";
				}
				currentprice.add(Double.parseDouble(sprice));
			}
		}
		System.out.println(currentprice);
		int worktemp[] = new int[workdayinfo.size()];
		for (int i = 0; i < workdayinfo.size(); i++) {
			worktemp[i] = workdayinfo.get(i)[0];
		}
		for (Price p : product.getPrices()) {
			if (!p.getTime().before(start) && !p.getTime().after(end)) {
				int index = (p.getTime().getYear() - start.getYear()) * 12
						+ p.getTime().getMonth() - start.getMonth();
				if (workdayinfo.get(index).length != 1
						&& p.getTime().getDate() >= workdayinfo.get(index)[1]) {
					index++;
				}
				worktemp[index]--;
				cp += p.getPrice();
			}
		}
		int top = 0, bottom = 0;
		for (int i = 0; i < currentprice.size(); i++) {
			cp += currentprice.get(i) * worktemp[i];
			top += worktemp[i];
			bottom += workdayinfo.get(i)[0];
			System.out.print(workdayinfo.get(i)[0]);
			System.out.print(' ');
		}
		System.out.println();
		System.out.println("Top: " + top + "\tBottom: " + bottom);
		risk = quantity * top;
		risk /= bottom;
		cp /= bottom;
		profit = cp - price;
		profit *= quantity;
		if (!buy) {
			risk *= -1;
			profit *= -1;
		}
	}

	public int getRisk() {
		return (int) risk;
	}

	public double getCp() {
		return cp;
	}

	public double getProfit() {
		return profit;
	}

	public String getFormatProfit() {
		return BaseAction.format(profit);
	}

}
